﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.DynamicData.ModelProviders;
using System.Collections.ObjectModel;
using NHibernate.Linq;

namespace Mpu.NHibernateDataModelProvider
{
    public class NHibernateDataModelProvider : DataModelProvider
    {
        private List<NHibernateTableProvider> tables = new List<NHibernateTableProvider>();

        public NHibernateDataModelProvider()
        {
            this.ContextType = typeof(GenericNHibernateContext);

            foreach (var item in NHibernateFactory.Current.Configuration.ClassMappings)
            {
                tables.Add(new NHibernateTableProvider(this, item));
            }

            Initialize();
        }

        public void Initialize()
        {
            foreach (var table in tables)
            {
                table.Initialize();
            }
        }

        public override object CreateContext()
        {
            return new GenericNHibernateContext();
        }

        public override ReadOnlyCollection<TableProvider> Tables
        {
            get { return tables.Cast<TableProvider>().ToList().AsReadOnly(); }
        }
    }
}
